package com.wunu.smartlock1.net;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.wunu.smartlock1.net.response.LoginResult;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class NetComponent {
    private static  Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd hh:mm:ss")
            .create();

    private static String BASE_URL = "https://lkviz3xv.qcloud.la/weapp/";

    private static String USER_URL = "https://api.iwunu.com/wunu-zn/appliance/user/";
    private static String USER_URL2 = "https://api.iwunu.com/wunu-app/appliance/user/";
    private static Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

    public static Retrofit UserRetrofit = new Retrofit.Builder()
            .baseUrl(USER_URL)
            .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
            .client( new OkHttpClient.Builder().build())
            .build();
    public static Retrofit UserRetrofit2 = new Retrofit.Builder()
            .baseUrl(USER_URL2)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();
    /**
     * 登录成功需要执行这个，以便后续请求头部能带上token
     * @param loginResult
     */
    public static  void addTokenInterceptor(final LoginResult loginResult) {
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder()
                        .addHeader("content-type", "application/json;charset=utf-8")
                        .addHeader("x-wx-skey", loginResult.getData().getToken())
                        .build();
                return chain.proceed(request);
            }
        });
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(httpClient.build())
                .build();
    }

    public static Retrofit getRetrofit() {
        return retrofit;
    }
}
